

package top.continew.admin.rpc;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.continew.admin.question.model.LearningSummary;
import top.continew.admin.question.service.LearningSummaryService;
import com.shengchao.examstar.rpc.question.api.ILearningSummaryRpc;
import com.shengchao.examstar.rpc.question.req.LearningSummaryReq;
import com.shengchao.examstar.rpc.question.resp.LearningSummaryResp;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * 学习总结RPC接口实现
 */
@Slf4j
@Service
@DubboService
public class LearningSummaryRpc implements ILearningSummaryRpc {

    @Autowired
    private LearningSummaryService learningSummaryService;

    /**
     * 生成学习总结
     * 同步方法，会等待AI生成完成
     *
     * @param req 学习总结请求对象
     * @return 学习总结结果
     * @throws ExecutionException   执行异常
     * @throws InterruptedException 中断异常
     */
    @Override
    public LearningSummaryResp generateSummary(LearningSummaryReq req) throws ExecutionException, InterruptedException {
        log.info("开始生成学习总结，用户ID: {}, 题集ID: {}", req.getUserId(), req.getQuestionSetId());

        try {
            // 生成学习总结并保存
            LearningSummary summary = learningSummaryService.generateSummary(req.getQuestionSetId(), req
                .getUserId(), req.getQuestionAndAnswer(), req.getKnowledge());

            // 转换为RPC响应对象
            LearningSummaryResp resp = convertToRpcResp(summary);
            if (resp == null) {
                return null;
            }
            log.info("学习总结生成成功，总结ID: {}", resp.getId());
            return resp;
        } catch (Exception e) {
            log.error("生成学习总结失败: {}", e.getMessage(), e);
            throw new ExecutionException("生成学习总结失败", e);
        }
    }

    /**
     * 查询学习总结
     *
     * @return 学习总结结果，如果不存在返回null
     * @throws ExecutionException   执行异常
     * @throws InterruptedException 中断异常
     */
    @Override
    public LearningSummaryResp querySummary(Long userId,
                                            Long questionSetId) throws ExecutionException, InterruptedException {

        try {
            // 查询学习总结
            LearningSummary summary = learningSummaryService.getByUserDoQuestionSetId(userId, questionSetId);

            if (summary == null) {
                return null;
            }

            // 转换为RPC响应对象
            LearningSummaryResp resp = convertToRpcResp(summary);
            log.info("学习总结查询成功，总结ID: {}", resp.getId());
            return resp;
        } catch (Exception e) {
            log.error("查询学习总结失败: {}", e.getMessage(), e);
            throw new ExecutionException("查询学习总结失败", e);
        }
    }

    /**
     * 将实体对象转换为RPC响应对象
     *
     * @param summary 学习总结实体
     * @return RPC响应对象
     */
    private LearningSummaryResp convertToRpcResp(LearningSummary summary) {
        if (summary == null) {
            return null;
        }

        LearningSummaryResp resp = new LearningSummaryResp();
        resp.setId(summary.getId());
        resp.setUserDoQuestionSetId(summary.getUserDoQuestionSetId());
        resp.setQuestionSetId(summary.getQuestionSetId());
        resp.setUserId(summary.getUserId());
        resp.setOverallAssessment(summary.getOverallAssessment());
        resp.setSummarize(summary.getSummarize());
        resp.setLearningSuggestions(summary.getLearningSuggestions());
        resp.setRecommendedLearning(summary.getRecommendedLearning());
        resp.setDate(summary.getDate());

        // 处理学习建议知识点列表
        if (summary.getLearningSuggestions() != null && !summary.getLearningSuggestions().isEmpty()) {
            List<LearningSummaryResp.KnowledgeItem> learningSuggestionsList = JSON.parseArray(summary
                .getLearningSuggestions(), LearningSummaryResp.KnowledgeItem.class);

            resp.setLearningSuggestionsList(learningSuggestionsList);
        } else {
            resp.setLearningSuggestionsList(new ArrayList<>());
        }

        // 处理推荐学习知识点列表
        if (summary.getRecommendedLearning() != null && !summary.getRecommendedLearning().isEmpty()) {
            List<LearningSummaryResp.KnowledgeItem> recommendedLearningList = JSON.parseArray(summary
                .getRecommendedLearning(), LearningSummaryResp.KnowledgeItem.class);

            resp.setRecommendedLearningList(recommendedLearningList);
        } else {
            resp.setRecommendedLearningList(new ArrayList<>());
        }

        return resp;
    }
}